import { reactControl, ReactViewState, ReactView, ReactViewControl } from "pao-aop-client";

import React from "react";
import moment from 'moment';
import { addon, Ref, getObject, log, Permission } from "pao-aop";
import SignFrameLayout, { InputType } from "src/business/style-components/sign-frame-layout";
import { NTOperationTable } from "src/business/components/operation-table";
import { CompanySign } from "src/models/companySign";
import { ISignService, AllSignCondition } from "src/models/signService";
import { change_structure, onRowSkipClick, ROUTE_PATH, isPermission } from "../../app/util-tool";
import { PermissionList } from "../../app/permission";
// import { Spin, Icon } from "antd";
moment.locale('zh-cn');
/**
 * 组件：全部标识视图状态
 */
export interface AllSignViewState extends ReactViewState {
    /** 全部标识列表数据源 */
    data_source?: CompanySign[];
    /** 当前第几页 */
    page?: number;
    /** 当前每页数 */
    pageSize?: number;
    /** 数据总条数 */
    total_data?: number;
    /** 查询条件对象 */
    condition?: AllSignCondition;
    /** 标识类型列表 */
    handle_map?: any;
    /** 滚动条 */
    loading?: boolean;
}
/**
 * 组件：全部标识视图
 * 描述
 */
export class AllSignView extends ReactView<AllSignViewControl, AllSignViewState> {
    private columns = [{
        title: '标识名称',
        dataIndex: 'handle_name',
        width: 450
    },
    {
        title: '标识类型',
        dataIndex: 'handle_type',
        width: 150,
        render: (text: string, record: any, index: any) => {
            let handle_map = this.state.handle_map;
            if (text && handle_map) {
                return handle_map.get(text) ? handle_map.get(text) : text;
            }
        }
    },
    {
        title: '标识',
        width: 450,
        dataIndex: 'handle_code', render: (text: string, record: any, index: any) => {
            let route = '';
            switch (record.handle_type) {
                case 'single_product':
                    route = ROUTE_PATH.singleProductDetailView;
                    break;
                case 'category':
                    route = ROUTE_PATH.categoryTemplateDetail;
                    break;
                case 'company':
                    route = ROUTE_PATH.companyTemplateDetail;
                    break;
                case 'external_links':
                    route = ROUTE_PATH.externalLinksDetail;
                    break;
                default:
                    null;
            }
            return <a onClick={() => onRowSkipClick(this.props, record, index, route)}>{text}</a>;
        }
    },
    {
        title: '创建时间',
        dataIndex: 'create_date',
        width: 150,
        render: ((create_date: Date) =>
            create_date.toString()
        )
    }];
    constructor(props: AllSignViewControl) {
        super(props);
        let handle_map = change_structure('name', [{ id: 'single_product', name: '单品标识' }, { id: 'category', name: '品类标识' }, { id: 'company', name: '企业标识' }, { id: 'external_links', name: '跳转' }]);
        this.state = {
            condition: {},
            page: 1,
            pageSize: 10,
            handle_map: handle_map,
            loading: false
        };
    }
    /** 分页回调事件 */
    pageOnCick = (contents: any) => {
        console.log('page:', contents);
        this.setState({
            page: contents,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, contents, this.state.pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("AllSignViewControl", error.message);
            });
    }
    /** 改变分页数量回调事件 */
    showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            pageSize: pageSize,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("AllSignViewControl", error.message);
            });
    }
    /** 自定义图标按钮回调事件 */
    onIconClick = (type: string, contents: any) => {
        if ('icon_edit' === type) {
            switch (contents.handle_type) {
                case 'single_product':
                    this.props.history!.push(ROUTE_PATH.changeSingleProductView + `/${contents.id}`);
                    break;
                case 'category':
                    this.props.history!.push(ROUTE_PATH.categoryTemplate + `/${contents.id}`);
                    break;
                case 'company':
                    this.props.history!.push(ROUTE_PATH.companyTemplateView + `/${contents.id}`);
                    break;
                case 'external_links':
                    this.props.history!.push(ROUTE_PATH.externalLinks + `/${contents.id}`);
                    break;
                default:
                    null;
            }
        }
    }
    /** 标识类别回调 */
    type_method = (value: any) => {
        this.setState({
            loading: true
        });
        let condition = this.state.condition;
        condition!.handle_type = value;
        this.queryList(condition ? condition : {}, 1, this.state.pageSize ? this.state.pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("AllSignViewControl", error.message);
            });
        this.setState({
            condition: condition
        });
    }
    getdataService?() {
        return getObject(this.props.ISignService_Fac!);
    }
    // 查询列表信息
    async queryList(condition: AllSignCondition, page: number, count: number) {
        let data = await this.getdataService!()!.get_all_list!(condition, page, count)!;
        this.setState({
            total_data: data ? data!.total : 0, // 取接口返回的总数
            data_source: data ? data!.result : []
        });
    }

    // 查询回调
    private search = (e: any, val: any) => {
        let condition = Object.assign(this.state.condition, val);
        console.log(condition);
        this.setState({
            condition: condition,
            page: 1,
            loading: true
        });
        this.queryList(condition, 1, this.state.pageSize ? this.state.pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("AllSignViewControl", error.message);
            });
    }
    // 重置回调
    private reset = () => {
        console.log("重置回调");
        let handle_type = this.state.condition!.handle_type;
        this.setState({
            condition: { handle_type }
        });
    }
    componentDidMount() {
        this.setState({
            loading: true
        });
        let condition: AllSignCondition = {};
        this.queryList(condition, 1, 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("AllSignViewControl", error.message);
            });
    }
    render() {
        const redeirect = isPermission ? isPermission!(PermissionList.AllSign_Select) : undefined;
        if (redeirect) {
            return redeirect;
        }
        let { data_source } = this.state;
        let sign_frame_props = {
            loading: this.state.loading,
            type_show: true,
            type_method: this.type_method,
            type_props: {
                label: '标识类型',
                data: [
                    {
                        key: 1,
                        text: '企业标识',
                        value: 'company'
                    },
                    {
                        key: 2,
                        text: '品类标识',
                        value: 'category'
                    },
                    {
                        key: 3,
                        text: '单品标识',
                        value: 'single_product'
                    },
                    {
                        key: 4,
                        text: '跳转标识',
                        value: 'external_links'
                    }
                ]
            },
            edit_form_items_props: [
                {
                    type: InputType.input,
                    label: "标识名称",
                    decorator_id: "handle_name",
                    option: {
                        placeholder: "请输入标识名称"
                    }
                },
                {
                    type: InputType.input,
                    label: "标识",
                    decorator_id: "handle_code",
                    option: {
                        placeholder: "请输入标识"
                    }
                },
                {
                    type: InputType.date,
                    label: "创建时间",
                    decorator_id: "create_date"
                },
            ],
            showTable: (
                <NTOperationTable
                    data_source={data_source}
                    columns_data_source={this.columns}
                    on_icon_click={this.onIconClick}
                    other_label_type={[{ type: 'icon', label_key: 'icon_edit', label_parameter: { icon: 'antd@edit' } }]}
                    table_size='middle'
                    showHeader={true}
                    bordered={false}
                    total={this.state.total_data}
                    default_page_size={10}
                    total_pages={Math.ceil((this.state.total_data ? this.state.total_data : 0) / 10)}
                    show_footer={true}
                    page_on_click={this.pageOnCick}
                    show_size_change={this.showSizeChange}
                    rowKey='id'
                />),
            search_cb: this.search,
            reset_cb: this.reset
        };
        return (
            <SignFrameLayout {...sign_frame_props} />

        );
    }
}

/**
 * 控件：全部标识视图控制器
 * 描述
 */
@addon('AllSignView', '全部标识视图', '描述')
@reactControl(AllSignView, true)
export class AllSignViewControl extends ReactViewControl {
    public ISignService_Fac?: Ref<ISignService>;
    /** 视图权限 */
    public permission?: Permission;
    /** 权限判断方法 */
    public isPermission?: (permission: Permission) => React.ReactNode | undefined;
}